const sqlite3 = require('sqlite3').verbose();
const path = require("path");
exports.getinfo = (sql)=>{//获取数据
    return new Promise(function(resolve,reject){
        var db = new sqlite3.Database(path.join(__dirname,"./WebpackVue.db"));
        db.serialize(()=>{
            db.all(sql, function(err, data) {
                if (err) {
                    reject(err);
                    return 
                }
                resolve(data);
            });            
        })
        db.close();        
    }) 
}
exports.setinfo = (sql)=>{
    return new Promise(function(resolve,reject){
        var db = new sqlite3.Database(path.join(__dirname,"./WebpackVue.db"));
        db.serialize(()=>{
            db.run(sql, function(err) {
                if (err) {
                    reject(err);
                    return 
                }
                resolve("数据更新成功");            
            });            
        })
        db.close();        
    }) 
}
function getfloor(obj){
    return new Promise(function(resolve,reject){
        var db = new sqlite3.Database(path.join(__dirname,"./WebpackVue.db"));
        var count;
        db.serialize(()=>{
            db.all(`select count(*) AS ID from Comments_list where type = '${obj.type}' and id = ${obj.id}`,function(err,data){
                count = data[0].ID;   
                resolve(count+1);  
            })
        })
        db.close();        
    }) 
}
exports.addCmtItem =(obj)=>{
    return new Promise((resolve,reject)=>{
        getfloor(obj).then((data)=>{
            var db = new sqlite3.Database(path.join(__dirname,"./WebpackVue.db"));
            db.serialize(()=>{
                db.run(`INSERT INTO Comments_list VALUES('${obj.type}',${obj.id},${data},'${obj.container}','${obj.time}','${obj.user}')`,function(err){
                    if(err){
                        reject(err)
                    }else{
                        resolve('ok');
                    }
                })
            })
        })
    })
}
exports.showCmtList = (obj)=>{
    return new Promise((resolve,reject)=>{
        var db = new sqlite3.Database(path.join(__dirname,"./WebpackVue.db"));
        db.serialize(()=>{        
            db.all(`select floor,container,uploadtime,user from Comments_list where type = '${obj.type}' and id = ${obj.id} order by floor desc`,function(err,data){
                if(err){
                    reject(err)
                }
                resolve(data)
            })
        })
        db.close();
    })
}

